package springboot.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import springboot.entity.LjhsCollector;
import springboot.entity.LjhsUser;
import springboot.service.ILjhsCollectorService;
import springboot.service.ILjhsUserService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class TokenUtil {
    private static ILjhsCollectorService staticCollectorService;
    @Resource
    private ILjhsCollectorService collectorService;
    @PostConstruct
    public void setCollectorService() {
        staticCollectorService = collectorService;
    }
    /**
     * 生成token
     * @return
     */
    public static String genToken(String collectorId,String sign){
        return JWT.create().withAudience(collectorId) // 将 user id 保存到 token 里面
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //2h后token过期
                .sign(Algorithm.HMAC256(sign));
    }
    public static LjhsCollector getCurrentCollector(){
        try {
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
        if (StrUtil.isNotBlank(token)) {

            String collectorId = JWT.decode(token).getAudience().get(0);
            return staticCollectorService.getById(Integer.valueOf(collectorId));
        }
            }catch (Exception e){
                return null;
            }
            return null;
        }
}
